package com.bike.controller.jump;

import java.math.BigDecimal;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bike.controller.BaseController;
import com.bike.entity.HhBusiness;
import com.bike.entity.HhDining;
import com.bike.entity.HhOpenUser;
import com.bike.entity.HhOrder;
import com.bike.entity.HhServiceConfig;
import com.bike.service.impl.HhBusinessServiceImpl;
import com.bike.service.impl.HhDiningServiceImpl;
import com.bike.service.impl.HhFoodTagServiceImpl;
import com.bike.service.impl.HhOrderServiceImpl;
import com.bike.service.impl.HhServiceConfigServiceImpl;
import com.bike.util.Constant;
import com.bike.util.PageData;
import com.topit.show.aliapi.AliUtil;
import com.topit.show.core.util.Sha1Util;
import com.topit.show.wxapi.common.WxPayUtil;

@Controller
@RequestMapping("jhh")
public class HhWxController extends BaseController{
	@Autowired
	private HhBusinessServiceImpl  hhBusinessServiceImpl;
	@Autowired
	private HhFoodTagServiceImpl  hhFoodTagServiceImpl;
	@Autowired
	private HhDiningServiceImpl  hhDiningServiceImpl;
	@Autowired
	private HhOrderServiceImpl  hhOrderServiceImpl;
	@Autowired
	private HhServiceConfigServiceImpl  hhServiceConfigServiceImpl;

	/**
	 * 跳转到列表页面
	 */
	@RequestMapping("getShopMenus")
	@ResponseBody
	public PageData toList(HttpServletRequest request){
		PageData pd=PageData.getToPageData(request);
		Long businessId=pd.getLong("businessId");
		PageData result=hhBusinessServiceImpl.selectShopMenus(businessId);
		return result;
	}
	/**
	 * 规格列表
	 * @param request
	 * @return
	 */
	@RequestMapping("getMutliType")
 	@ResponseBody
 	public Map<String,Object> getMutliType(HttpServletRequest request){
 		try {
 			PageData pd=PageData.getPageDataByPage(request);
 			if(pd.getLong("foodId")>0){
 				Map<String,Object> result=getSuccessMap();
 				result.put("foodTags", hhFoodTagServiceImpl.selectByFoodId(pd.getLong("foodId")));
 				return result;
 			}
 		} catch (Exception e) {
 			e.printStackTrace();
 		}
 		return getErrorMap("失败");
 	}
	/**
	 * 跳到购物车
	 * @param request
	 * @return
	 */
	@RequestMapping("toShopping")
	public  String  toShopping(HttpServletRequest request,Model model){
		try {
			PageData pd=PageData.getPageDataByPage(request);
			HhDining dining=hhDiningServiceImpl.selectByHhDiningId(pd.getLong("dining"));
			pd.put("businessId", dining.getBusinessId());
			HhServiceConfig serviceConfig=hhServiceConfigServiceImpl.selectServciFee(null,pd);
			
			pd.put("serviceFee", serviceConfig.getServiceFee());
			HhBusiness business=hhBusinessServiceImpl.selectByHhBusinessId(dining.getBusinessId());
			pd.put("withFee",business.getPayWithdraw() );
			model.addAttribute("dining", dining);
			model.addAttribute("pd", pd);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/information/h5/shopping_list" ;
	}
	/**
	 * 跳转到订单列表
	 * @param request
	 * @return
	 */
	@RequestMapping("toOrderList")
	public  String  toOrderList(HttpServletRequest request,Model model){
		try {
			PageData pd=PageData.getPageDataByPage(request);
			HhOpenUser user=(HhOpenUser) request.getSession().getAttribute("h5user");
			model.addAttribute("user", user);
			model.addAttribute("pd", pd);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/information/h5/order_list" ;
	}
	/**
	 *  订单列表数据
	 * @param request
	 * @return
	 */
	@RequestMapping("getOrderList")
	@ResponseBody
	public  PageData  getOrderList(HttpServletRequest request,Model model){
		
		try {
			PageData pd=PageData.getPageDataByPage(request);
			HhOpenUser user=(HhOpenUser) request.getSession().getAttribute("h5user");
			 
			PageData hhOrders=hhOrderServiceImpl.selectHhOrderListAndItem(pd);
			
			return getSuccessPd(hhOrders);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return getErrorPd("系统异常");
	}
	/**
	 *  删除订单
	 * @param request
	 * @return
	 */
	@RequestMapping("deleteOrder")
	@ResponseBody
	public  PageData  deleteOrder(HttpServletRequest request,Model model){
		
		try {
			PageData pd=PageData.getPageDataByPage(request);
			HhOpenUser user=(HhOpenUser) request.getSession().getAttribute("h5user");
			pd.put("userId", user.getOpenUserId());
			 PageData pData=hhOrderServiceImpl.updateOrderDelete(pd);
			
			return getErrorPd(pData);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return getSuccessPd();
	}
	/**
	 *  支付结果页面
	 * @param request
	 * @return
	 */
	@RequestMapping("payResult")
	public  String  payResult(HttpServletRequest request,Model model){
		PageData pd=PageData.getPageDataByPage(request);
		long orderId=pd.getLong("orderId");
		String action=pd.getString("action");
		
		model.addAttribute("pd", pd);
		return "/information/h5/pay_result";
	}
	/**
	 * 下单
	 * @param request
	 * @return
	 */
	@RequestMapping("saveOrder")
	@ResponseBody
	public  PageData  saveOrder(HttpServletRequest request,Model model){
		PageData pd=PageData.getPageDataByPage(request);
		PageData result=getSuccessPd();
		try {
			HhOpenUser user=(HhOpenUser) request.getSession().getAttribute("h5user");
			if(user==null){
				return getErrorPd("用户登录失效,请重新登录");
			}
			//下单
			HhOrder  data=hhOrderServiceImpl.insertOrder(pd,user);
			/*	long  payway=System.currentTimeMillis()%2+1;
			pd.put("payway",payway);
			pd.put("trade_no","trade_no");
			pd.put("transaction_id","transaction_id");
			pd.put("buyer_id","buyer_id");
			pd.put("channel",payway==1?"微信下单":"支付宝下单");
			hhOrderServiceImpl.updateOrderSuccess(pd, data);
			if(pd!=null)
			return getErrorPd("已经结账");*/
//			data=(HhOrder) pd.get("33");
//			if(data!=null){
				//微信
				if( request.getHeader("User-Agent").indexOf(Constant.wxAgent) > 0){
					//获取微信payJson
					String prepayId=WxPayUtil.getPrePayId(data.getOpenid(), Constant.business, Constant.serviceType, String.valueOf(data.getOrderId()), data.getTotalPrice().multiply(new BigDecimal(100)).intValue(), getClientIp(request), data.getBusinessId().toString());
					String payJson=WxPayUtil.getPayJson(prepayId, null);
					result.put("payJson", payJson);
					result.put("channel", "wx");
				}else{
					result.put("channel", "ali");
				}
				result.put("orderId", data.getOrderId());
//			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return  result ;
	}
	/**
	 * 支付订单
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("payOrder")
	@ResponseBody
	public  PageData  payOrder(HttpServletRequest request,Model model){
		PageData pd=PageData.getPageDataByPage(request);
		PageData result=getSuccessPd();
		try {
			HhOpenUser user=(HhOpenUser) request.getSession().getAttribute("h5user");
			if(user==null){
				return getErrorPd("用户登录失效,请重新登录");
			}
			//下单
			HhOrder order=hhOrderServiceImpl.selectByHhOrderId(pd.getLong("orderId"));
			if(order!=null&&order.getPayStatus()==0){
				//微信
				if( request.getHeader("User-Agent").indexOf(Constant.wxAgent) > 0){
					result.put("channel", "wx");
				}else{
					result.put("channel", "ali");
				}
				result.put("orderId", order.getOrderId());
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return  getErrorPd("支付失败,请刷新页面重新支付") ;
	}
	/**
	 * 去支付宝支付
	 * @param request
	 * @return
	 */
	@RequestMapping("toAliPay")
	public  void  toAliPay(HttpServletRequest request,Model model,HttpServletResponse httpResponse){
		PageData pd=PageData.getPageDataByPage(request);
		PageData result=getSuccessPd();
		try {
			HhOpenUser user=(HhOpenUser) request.getSession().getAttribute("h5user");
			if(user==null){
				return ;
			}
			HhOrder order=hhOrderServiceImpl.selectByHhOrderId( pd.getLong("orderId"));
			
			String form=AliUtil.getPayForm(user,pd,order);
			httpResponse.setContentType("text/html;charset=utf-8" );
			httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
			httpResponse.getWriter().flush();
			httpResponse.getWriter().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 微信payjson
	 * @param userId
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("wxJson")
	@ResponseBody
	public Map<String,Object> wxPay(  HttpServletRequest request,Model model){
		PageData pd=PageData.getPageDataByPage(request);
		HhOpenUser openUser= (HhOpenUser) request.getAttribute(Constant.h5User);
		HhOrder order=hhOrderServiceImpl.selectByHhOrderId(pd.getLong("orderId"));
		if(order.getUserId()!=openUser.getOpenUserId()){
			return getErrorMap("无权操作");
		}
		String openId=openUser.getOpenId();
		String attach=order.getBusinessId().toString();
		String orderId=order.getOrderId().toString();
		String ip = getClientIp(request);
		String prepay_id = WxPayUtil.getPrePayId(openId, "呼呼订单", 1, orderId, 1, ip,attach);
		
		Map<String,Object> result=this.getSuccessMap();
		result.put("payJson", WxPayUtil.getPayJson(prepay_id, Sha1Util.getNonceStr()));
		
		return result;
	}
}
